package com.vito.oa.act.extend.action;

import java.text.MessageFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.dubbo.config.annotation.Reference;
import com.vito.base.authoriza.action.BaseAction;
import com.vito.base.authoriza.cache.SessionMap;
import com.vito.base.authoriza.model.BaseSql;
import com.vito.base.authoriza.model.UserModel;
import com.vito.base.authoriza.service.BaseSqlService;
import com.vito.base.authoriza.service.SQLAdapterService;
import com.vito.base.model.ResMsg;
import com.vito.base.model.Result;
import com.vito.base.util.Contants;
import com.vito.base.util.Validata;
import com.vito.oa.act.extend.service.OaActProgressTableService;
import com.vito.oa.act.extend.service.OaActivitiMainService;
import com.vito.oa.act.model.OaActCommentModel;
import com.vito.oa.act.service.OaActCommentService;
import com.vito.oa.act.service.OaActApproverServer;

@Controller
@RequestMapping("oa/act/activitiMain")
public class OaActivitiMainAction extends BaseAction {
	@Reference(group="OaActivitiMainServiceImpl")
	private OaActivitiMainService activitiMainService;
	@Reference
	private OaActProgressTableService actProgressTableService;
	@Reference
	private OaActCommentService oaActCommentService;
	@Reference
	private OaActApproverServer oaActApproverServer;
	@Reference
	private SQLAdapterService sqlAdapterService;
	@Reference
	private BaseSqlService baseSqlServicel;

	/**
	 * web端-获取审批表单
	 * @param key
	 * @param processInstanceId
	 * @param taskId
	 * @param baseSql
	 * @param param
	 * @return
	 */
	@RequestMapping("getProcessPage")
	public ModelAndView getProcessPage(String key, String processInstanceId, String taskId, BaseSql baseSql,
			String[] param) {
		UserModel user = SessionMap.getObj();
		ModelAndView mv;
		if (Validata.isNullOrEmpty(processInstanceId)) {
			mv = new ModelAndView("com/vito/oa/act/action/view/newApprovelPageTemple");
		} else {
			mv = new ModelAndView("com/vito/oa/act/action/view/pageTemple");
		}
		Map<String, Object> res;
		try {
			if (user == null || Validata.isNullOrEmpty(user.getUserId())) {
				res = new HashMap<String, Object>();
				mv.addAllObjects(res);
				return mv;
			}
			res = activitiMainService.getProcessPage(user, key, processInstanceId);
			if (res == null) {
				res = new HashMap<String, Object>();
			}
			if (processInstanceId != null && !"".equals(processInstanceId)) {
				res.put(Contants.FORM_KEY_PROCESSINSTANCEID, processInstanceId);
			}
			if (taskId != null && !"".equals(taskId)) {
				res.put(Contants.FORM_KEY_TASKID, taskId);
			}
			// 查询评论 检查是否有@我
			if (res.get(Contants.FORM_KEY_BUSENESSID) != null) {
				OaActCommentModel oaActCommentModel = new OaActCommentModel();
				oaActCommentModel.setCreateUser(user.getUserId());
				oaActCommentModel.setBusinessId(res.get(Contants.FORM_KEY_BUSENESSID).toString());
				List<OaActCommentModel> commentList = oaActCommentService.getCommentList(oaActCommentModel);
				res.put("commentList", commentList);
			}
			if(processInstanceId == null){
				// 查询流程条件col
				List<Map<String, String>> branchList = oaActApproverServer.queryProcessBranchList(key,
						user.getDeptParentId());
				if (branchList.size() > 0) {
					String colId = branchList.get(0).get("tableKey") + "-" + branchList.get(0).get("branchVaId");
					res.put("branchCol", colId);
				}

				if (baseSql != null && Validata.notNullOrEmpty(baseSql.getQueryId())) {
					List<Map<?, ?>> defaultData = sqlAdapterService.getDataBysql(baseSql, false, param);
					res.put("defaultData", defaultData);
				}
			}
			mv.addAllObjects(res);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return mv;
	}


	/**
	 * web端-获取审批信息
	 */
	@RequestMapping("getProcessViewPage")
	public ModelAndView getProcessViewPage(String key, String bussId) {
		UserModel user = SessionMap.getObj();
		ModelAndView mv = new ModelAndView("com/vito/oa/act/action/view/pageTemple");
		if (user == null || Validata.isNullOrEmpty(user.getUserId())) {
			mv.addAllObjects(new HashMap<String, Object>());
			return mv;
		}
		Map<String, Object> res = activitiMainService.getProcessViewPage(user, key, bussId);
		if (res == null) {
			res = new HashMap<String, Object>();
		}
		mv.addAllObjects(res);
		return mv;
	}

	/**
	 * 审批单提交
	 */
	@RequestMapping("saveProcessData")
	public @ResponseBody Result saveProcessData(@RequestBody Map<String, Map<String, Object>> data) {
		UserModel user = SessionMap.getObj();
		Result res = new Result();
		try {
			if (user == null || Validata.isNullOrEmpty(user.getUserId())) {
				res.setCode(Result.CODE_LOGIN_REQUIRE);
				res.setMsg(ResMsg.MSG_LOGIN_NEED);
				return res;
			}
			res = activitiMainService.saveProcessData(user, data);
		} catch (RuntimeException re) {
			//re.printStackTrace();
			res = saveProcessDataAndEnd(data,re);
			if(res != null){
				return res;
			}

		} catch (Exception e) {
			e.printStackTrace();
			res.setCode(Result.CODE_ERROR);
			res.setMsg("处理异常");
			return res;
		}
		return res;
	}
	private Result saveProcessDataAndEnd ( Map<String, Map<String, Object>> data,RuntimeException re){
		UserModel user = SessionMap.getObj();
		Result res = new Result();
		try {
			String msg = re.getMessage();
			if(null == msg){
				return null;
			}
			if ( msg.startsWith("org.activiti.engine.ActivitiException") ||
					msg.startsWith("org.activiti.engine.ActivitiIllegalArgumentException")) {
				res = activitiMainService.saveProcessDataAndEndProcess(user, data);
				return res;
			} else if(msg.startsWith("org.activiti.engine.ActivitiObjectNotFoundException")){
				res.setMsg("重新加载审批信息");
				res.setCode(Result.CODE_PARA_ERROR);
				return res;
			}
			else {
				int start = msg.indexOf("java.lang.RuntimeException:");
				if (start >= 0) {
					int end = msg.indexOf("\n");
					msg = msg.substring(start, end);
					start = msg.indexOf(":");
					msg = msg.substring(start + 1);
					res.setMsg(msg);
				} else {
					res.setMsg(msg);
				}
				res.setCode(Result.CODE_ERROR);
			}
		} catch (Exception e2) {
			e2.printStackTrace();
			res.setCode(Result.CODE_ERROR);
			res.setMsg("处理异常");
			return res;
		}
		return null;
	}

	/**
	 * 挂起或解挂任务
	 * 
	 * @param processInstanceId
	 *            流程实例id
	 * @param isHangUp
	 *            true挂起，false解挂
	 * @return
	 */
	@RequestMapping("hangUp")
	public @ResponseBody Result hangUp(String businessId, String processInstanceId, boolean isHangUp) {
		Result res = new Result();
		UserModel user = SessionMap.getObj();
		if(user == null || Validata.isNullOrEmpty(user.getUserId())){
			res.setCode(Result.CODE_LOGIN_REQUIRE);
			res.setMsg(ResMsg.MSG_LOGIN_NEED);
			return res;
		}
		res= actProgressTableService.hangUp(user, businessId, processInstanceId, isHangUp);
		return res;
	}

	/**
	 * 终止任务
	 * 
	 * @param taskId
	 *            任务id
	 * @return
	 */
	@RequestMapping("endProcess")
	public @ResponseBody Result endProcess(@RequestBody Map<String, Map<String, Object>> data){
		Result res = new Result();
		try {
			UserModel user = SessionMap.getObj();
			if(user == null || Validata.isNullOrEmpty(user.getUserId())){
				res.setCode(Result.CODE_LOGIN_REQUIRE);
				res.setMsg(ResMsg.MSG_LOGIN_NEED);
				return res;
			}
			res= actProgressTableService.endProcess(user,data);
		} catch (Exception e) {
			res.setCode(Result.CODE_ERROR);
			res.setMsg(ResMsg.EXECERR);
			e.printStackTrace();
		}
		
		return res;
	}
	/**
	 * 手机端流程处理界面数据
	 * 
	 * @param key
	 * @param processInstanceId
	 * @param taskId
	 * @return
	 */
	@RequestMapping("getMobileProcessPage")
	public @ResponseBody Result getMobileProcessPage(String key, String processInstanceId, String taskId) {
		UserModel user = SessionMap.getObj();
		Result result = new Result();
		Map<String, Object> res;
		try {
			if (user == null || Validata.isNullOrEmpty(user.getUserId())) {
				result.setCode(Result.CODE_LOGIN_REQUIRE);
				result.setMsg(ResMsg.MSG_LOGIN_NEED);
				return result;
			}
			if (Validata.isNullOrEmpty(key)) {
				result.setCode(Result.CODE_PARA_ERROR);
				result.setMsg(MessageFormat.format(ResMsg.MSG_DATA_NEED, "流程key"));
				return result;
			}
			res = activitiMainService.getProcessPage(user, key, processInstanceId);
			if (res == null) {
				res = new HashMap<String, Object>();
			}
			if (processInstanceId != null && !"".equals(processInstanceId)) {
				res.put(Contants.FORM_KEY_PROCESSINSTANCEID, processInstanceId);
			}
			if (taskId != null && !"".equals(taskId)) {
				res.put(Contants.FORM_KEY_TASKID, taskId);
			}
			// 查询流程条件col
			List<Map<String, String>> branchList = oaActApproverServer.queryProcessBranchList(key,
					user.getDeptParentId());
			if (branchList.size() > 0) {
				String colId = branchList.get(0).get("tableKey") + "-" + branchList.get(0).get("branchVaId");
				res.put("branchCol", colId);
			}
			result.setData(res);
			result.setCode(Result.CODE_OK);
		} catch (Exception e) {
			result.setCode(Result.CODE_ERROR);
			result.setMsg(ResMsg.EXECERR);
			e.printStackTrace();
		}

		return result;
	}

	/**
	 * 手机端流程查看界面数据
	 * 
	 * @param key
	 * @param bussId
	 * @return
	 */
	@RequestMapping("getMobileProcessViewPage")
	public @ResponseBody Result getMobileProcessViewPage(String key, String bussId) {
		UserModel user = SessionMap.getObj();
		Result result = new Result();
		try {
			if (user == null || Validata.isNullOrEmpty(user.getUserId())) {
				result.setCode(Result.CODE_PARA_ERROR);
				result.setMsg(ResMsg.MSG_LOGIN_NEED);
				return result;
			}
			if (Validata.isNullOrEmpty(key)) {
				result.setCode(Result.CODE_PARA_ERROR);
				result.setMsg(MessageFormat.format(ResMsg.MSG_DATA_NEED, "流程key"));
				return result;
			}
			if (Validata.isNullOrEmpty(bussId)) {
				result.setCode(Result.CODE_PARA_ERROR);
				result.setMsg(MessageFormat.format(ResMsg.MSG_DATA_NEED, "流程bussId"));
				return result;
			}
			result.setData(activitiMainService.getProcessViewPage(user, key, bussId));
			result.setCode(Result.CODE_OK);
		} catch (Exception e) {
			result.setCode(Result.CODE_ERROR);
			result.setMsg(ResMsg.EXECERR);
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 手机端流程查看界面数据
	 * 
	 * @param key
	 * @param bussId
	 * @return
	 */
	@RequestMapping("getProcessData")
	public @ResponseBody Result getProcessData(String key, String bussId) {
		Result result = new Result();
		try {
			if (Validata.isNullOrEmpty(key)) {
				result.setCode(Result.CODE_PARA_ERROR);
				result.setMsg(MessageFormat.format(ResMsg.MSG_DATA_NEED, "流程key"));
				return result;
			}
			if (Validata.isNullOrEmpty(bussId)) {
				result.setCode(Result.CODE_PARA_ERROR);
				result.setMsg(MessageFormat.format(ResMsg.MSG_DATA_NEED, "流程bussId"));
				return result;
			}
			result.setData(activitiMainService.getProcessData(key, bussId));
			result.setCode(Result.CODE_OK);
		} catch (Exception e) {
			result.setCode(Result.CODE_ERROR);
			result.setMsg(ResMsg.EXECERR);
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 转交
	 * @param taskId
	 * @param userId
	 * @return
	 */
	@RequestMapping("transfer")
	@ResponseBody
	public Result transfer(String taskId, String userId) {
		Result rs = new Result();
		UserModel user = SessionMap.getObj();
		try {
			if (user == null) {
				rs.setCode(Result.CODE_LOGIN_REQUIRE);
				rs.setMsg(ResMsg.MSG_LOGIN_NEED);
				return rs;
			}
			if (userId.equals(user.getUserId())) {
				rs.setCode(Result.CODE_ERROR);
				rs.setMsg("不能转交给自己");
				return rs;
			}
			activitiMainService.transfer(taskId, userId);
			rs.setCode(Result.CODE_OK);
			rs.setMsg("转交成功");
		} catch (Exception e) {
			rs.setMsg("请求失败！");
			rs.setCode(Result.CODE_ERROR);
		}
		return rs;

	}
	
	@ResponseBody
	@RequestMapping("fasterCommit")
	public Result fasterCommit(String businessId,String taskId){
		UserModel user = SessionMap.getObj();
		Result rs = new Result();
		try{
			activitiMainService.fasterCommit(user,businessId,taskId);
			rs.setCode(Result.CODE_OK);
			rs.setMsg(ResMsg.EXE_SUCCESS);
		}catch (RuntimeException re) {
			Map<String ,Map<String ,Object>> data = activitiMainService.packSimpleCommitForm(businessId,taskId);
			rs = saveProcessDataAndEnd(data,re);
			if(rs != null){
				return rs;
			}

		} catch (Exception e) {
			e.printStackTrace();
			rs.setCode(Result.CODE_ERROR);
			rs.setMsg("处理异常");
			return rs;
		}
		return rs;
	}
	@ResponseBody
	@RequestMapping("fasterEnd")
	public Result fasterEnd(String businessId,String taskId){
		UserModel user = SessionMap.getObj();
		Result rs = new Result();
		try{
			activitiMainService.fasterEnd(user,businessId,taskId);
			rs.setCode(Result.CODE_OK);
			rs.setMsg(ResMsg.EXE_SUCCESS);
		}catch(Exception e){
			rs.setMsg(ResMsg.EXECERR);
			rs.setCode(Result.CODE_ERROR);
		}
		return rs;
	}
}
